package com.atlin.project.fileService.service;

import com.atlin.project.common.ErrorCode;
import com.atlin.project.config.AtLinConfig;
import com.atlin.project.exception.BusinessException;
import com.atlin.project.exception.ThrowUtils;
import com.atlin.project.fileService.BaseFileService;
import com.atlin.project.model.domain.SysUser;
import com.atlin.project.model.enums.FileUploadBizEnum;
import com.atlin.project.utils.file.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author atlin
 * @description minio文件存储服务
 * @createDate 2025/1/1 9:47
 */
@Component
@Slf4j
public class MinioFileService extends BaseFileService {

    @Resource
    private AtLinConfig atLinConfig;

    @Resource
    private MinioUtil minioUtil;

    @Value("${minio.bucket-name}")
    private String bucketName;


    @Override
    public AtLinConfig getConfig() {
        return atLinConfig;
    }

    @Override
    public String doSave(MultipartFile multipartFile, SysUser loginUser, FileUploadBizEnum fileUploadBizEnum) {
        configCheck();
        fileCheck(fileUploadBizEnum, multipartFile);

        String uuid = RandomStringUtils.randomAlphanumeric(8);
        String fileName = uuid + "-" + multipartFile.getOriginalFilename();

        String filePath = buildPath(loginUser.getId(), fileUploadBizEnum.getValue());
        String finalFileName = filePath + '/' + fileName;
        try {
            String preObjectUrl = minioUtil.putObject(finalFileName, multipartFile);
            log.info("[MinIo文件服务] {}", preObjectUrl);
            return preObjectUrl;
        } catch (Exception e) {
            log.error("[MinIo文件服务异常] ", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        }
    }

    @Override
    public void doRead(String path, HttpServletRequest request, HttpServletResponse response) {
        ThrowUtils.throwIf(StringUtils.isBlank(path), ErrorCode.PARAMS_ERROR);
        
        String regex = bucketName + '/' + atLinConfig.getBucket() + "[^?]*";
        // 编译正则表达式
        Pattern pattern = Pattern.compile(regex);
        // 创建matcher对象
        Matcher matcher = pattern.matcher(path);
        if (matcher.find()) {
            path = matcher.group().substring(bucketName.length());
        }

        try {
            minioUtil.getObject(path, response);
        } catch (Exception e) {
            log.error("[MinIo文件服务异常，文件读取失败] ", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件获取失败");
        }
    }
}
